package ua.kharkov.khpi.tarasenko.bach.web.command;

import java.util.Locale;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;

import ua.kharkov.khpi.tarasenko.bach.core.Constant;
import ua.kharkov.khpi.tarasenko.bach.core.LocalizedResourceManager;
import ua.kharkov.khpi.tarasenko.bach.core.EShopException;

/**
 * Root class for commands.
 * 
 * @author oleksandr
 * 
 */
public abstract class Command {
	private static final Logger log = Logger.getLogger(Command.class);

	/**
	 * Executes the command.
	 * 
	 * @return the address to forward request.
	 * 
	 * @throws EShopException
	 *             if error occurred
	 */
	public abstract String execute(HttpServletRequest request,
			HttpServletResponse response) throws EShopException;

	@Override
	public String toString() {
		return this.getClass().getSimpleName();
	}

	/**
	 * Handles errors that can be occurred by incorrect input data.
	 * 
	 * @param request
	 *            .
	 * @param errorMessage
	 *            .
	 * @return forward - url to forward request for further processing.
	 */
	protected String processError(HttpServletRequest request,
			String errorMessage) {
		String forward = Constant.PAGE_ERROR;
		request.setAttribute(Constant.ATTRIBUTE_ERROR_MESSAGE, errorMessage);
		if (log.isTraceEnabled()) {
			log.trace("Set request attribute "
					+ Constant.ATTRIBUTE_ERROR_MESSAGE + "=" + errorMessage);
		}

		return forward;
	}

	/**
	 * Return Localized Resource Manager for preferable locale from session
	 * (Constant.ATTRIBUTE_PREFERABLE_LOCALE). If it isn't specified Locale will
	 * be taken from request
	 * 
	 * @param request
	 *            ;
	 * @return LRManager - LocalizedResourceManager;
	 * 
	 */
	protected LocalizedResourceManager getLocalizedResourceManager(
			HttpServletRequest request) {

		HttpSession session = request.getSession(false);
		Object localeObj = null;
		if (session != null) {
			localeObj = session
					.getAttribute(Constant.ATTRIBUTE_PREFERABLE_LOCALE);
		}

		Locale locale = null;
		if (localeObj != null) {
			locale = new Locale((String)localeObj);
		} else {
			
			// Get Locale from request
			locale = request.getLocale();
		}

		// Create LocalizedResourceManager to get localized error messages
		LocalizedResourceManager LRManager = new LocalizedResourceManager(
				locale);

		return LRManager;
	}
}